package com.sunshine.util;

import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import sunshine.commcon.util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

@Slf4j
public class TokenUtil {
    public static Long getUserIdFromRequest(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        log.info("从请求头中获取token: {}", token);
        
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            log.info("处理后的token: {}", token);

            if (JwtUtil.validate(token)) {
                JSONObject payloads = JwtUtil.getJSONObject(token);
                log.info("从token中解析出的载荷: {}", payloads);
                Object userIdObj = payloads.get("id");

                if (userIdObj != null) {
                    log.info("从token中解析出的用户ID: {}", userIdObj);
                    return Long.parseLong(userIdObj.toString());
                } else {
                    log.warn("token中未找到用户ID");
                }
            } else {
                log.warn("token验证失败");
            }
        } else {
            log.warn("请求头中无有效token或token格式不正确");
        }
        return null;
    }
}